const express = require("express");
const doctorRouter = express.Router();
const DB = require("./../db/config");
const upload = require("./../db/uploadconfig");
module.exports = doctorRouter;

/**
 * 添加医生
 * @param {String} dname 医生名称 required
 * @param {String} dsex 医生性别 required '男|女'
 * @param {String} dsid 医生身份证，18位 required
 * @param {String} dtel 医生电话，11位 required
 * @param {String} dfeaturs 医生特长 required
 * @param {Number} jid 职称ID required
 * @param {String} dphoto 医生头像 required
 *
 */
doctorRouter.route("/doctor/add").post(upload.single("dphoto"), (req, res) => {
  let { dname, dsex, dsid, dtel, dfeaturs, jid } = req.body;
  let dphoto = req.file.filename;

  let sql = `insert into doctorstable (dname, dsex, dsid, dtel,dfeaturs, jid,dphoto) values(?,?,?,?,?,?,?);`;
  let param = [dname, dsex, dsid, dtel, dfeaturs, jid, dphoto];
  let cb = (err, data) => {
    if (!err) {
      res.json({ code: 0, msg: "添加医生信息成功", data: [] });
    } else {
      res.json({ code: 4002, msg: "添加医生信息失败", data: [] });
    }
  };
  DB.connect(sql, param, cb);
});

/**
 * 获取所有医生数据列表-后端分页
 * 多条件搜索接口
 * @param {Number} limit 一页几条 required
 * @param {Number} page 第几页 required
 * @param {String} doctorName 医生名称
 * @param {String} doctorSex 医生性别
 * @param {Number} doctorJob 职称ID
 */
doctorRouter.route("/doctor/list").get(function (req, res) {
  let { doctorName, doctorJob, doctorSex, limit, page } = req.query;

  limit = Number(limit);
  let startIndex = (page - 1) * limit;

  // 多条件查询 ，做同时满足条件的判断；
  let p1 = new Promise((resolve, reject) => {
    let param = [];
    let sql = `select * from doctorstable where 1=1`;

    if (doctorName !== "") {
      sql = sql + " and dname like ?";
      param.push("%" + doctorName + "%");
    }
    if (doctorJob !== "") {
      sql = sql + " and jid = ?";
      param.push(doctorJob);
    }
    if (doctorSex !== "") {
      sql = sql + " and dsex = ?";
      param.push(doctorSex);
    }
    sql = sql + " limit ?,?;";
    param.push(startIndex, limit);

    let cb = (err, data) => {
      console.log(err);
      if (err === null) {
        resolve({ code: 0, msg: "搜索成功", data });
      } else {
        reject({ code: 4002, msg: "搜索失败", data: [] });
      }
    };

    DB.connect(sql, param, cb);
  });
  // 查询总条数
  let p2 = new Promise((resolve, reject) => {
    let paramall = [];

    let sqlAll = `select * from doctorstable where 1=1`;

    if (doctorName !== "") {
      sqlAll = sqlAll + " and dname = ?";
      paramall.push(doctorName);
    }
    if (doctorJob !== "") {
      sqlAll = sqlAll + " and jid = ?";
      paramall.push(doctorJob);
    }
    if (doctorSex !== "") {
      sqlAll = sqlAll + " and dsex = ?";
      paramall.push(doctorSex);
    }

    let cbAll = (err, data) => {
      console.log(err);
      if (err === null) {
        resolve({ code: 0, count: data.length, msg: "搜索成功" });
      } else {
        reject({ code: 4002, count: 0, msg: "搜索失败" });
      }
    };
    DB.connect(sqlAll, paramall, cbAll);
  });
  Promise.all([p1, p2])
    .then((data) => {
      let obj = { ...data[0], ...data[1] };
      res.json(obj);
    })
    .catch((data) => {
      // console.log(data);
      let obj = { ...data[0], ...data[1] };
      res.json(obj);
    });
});

/**
 * 删除医生
 * @param {Number} did 医生ID required
 */
doctorRouter.route("/doctor/delete").post((req, res) => {
  let did = req.body.did;
  let sql = "delete from doctorstable where did = ?;";
  let param = [did];
  let cb = (err, data) => {
    if (!err) {
      res.json({ code: 0, msg: "删除医生成功", data: [] });
    } else {
      res.json({ code: 4002, msg: "删除医生失败", data: [] });
    }
  };
  DB.connect(sql, param, cb);
});

/**
 * 修改医生
 * @param {String} dname 医生名称 required
 * @param {String} dsex 医生性别 required '男|女'
 * @param {String} dsid 医生身份证，18位 required
 * @param {String} dtel 医生电话，11位 required
 * @param {String} dfeaturs 医生特长 required
 * @param {Number} jid 职称ID required
 * @param {Number} did 医生ID required 
 * @param {String} dphoto 医生头像 
 */
doctorRouter
  .route("/doctor/modify")
  .post(upload.single("dphoto"), (req, res) => {
    let { dname, dsex, dsid, dtel, dfeaturs, jid, did } = req.body;
    console.log(dname, dsex, dsid, dtel, dfeaturs, jid, did);
    console.log(req.file);
    let sql = "";
    let param = [];
    if (!req.file) {
      sql = `update doctorstable set dname =?, dsex=?, dsid=?, dtel=?,dfeaturs=?, jid=? where did =?;`;
      param = [dname, dsex, dsid, dtel, dfeaturs, jid, did];
    } else {
      let dphoto = req.file.filename;
      sql = `update doctorstable set dname =?, dsex=?, dsid=?, dtel=?,dfeaturs=?, jid=?,dphoto=? where did =?;`;
      param = [dname, dsex, dsid, dtel, dfeaturs, jid, dphoto, did];
    }

    let cb = (err, data) => {
      console.log(err);
      if (!err) {
        res.json({ code: 0, msg: "修改医生信息成功", data: [] });
      } else {
        res.json({ code: 4002, msg: "修改医生信息失败", data: [] });
      }
    };
    DB.connect(sql, param, cb);
  });

/**
 * 获取一个医生的详细信息
 * @param {Number} did 医生ID required
 */
doctorRouter.route("/doctor/info").get((req, res) => {
  let did = req.query.did;
  let sql = "select * from doctorstable where did = ?;";
  let param = [did];
  let cb = (err, data) => {
    if (!err) {
      res.json({ code: 0, msg: "查询医生信息成功", data });
    } else {
      res.json({ code: 4002, msg: "查询医生信息失败", data });
    }
  };
  DB.connect(sql, param, cb);
});

/**
 * 获取所有医生的数据
 * @method 'get'
 */
doctorRouter.route("/doctor/noteamall").get((req, res)=>{
  let sql = "select * from doctorstable as dct join jobs as j on dct.jid = j.jid WHERE did  NOT IN(SELECT DISTINCT did FROM teamdoctortable);"
  let cb = (err, data)=>{
    if (!err) {
      res.json({code :0, msg:"查询所有医生的数据成功",data})
    } else {
      res.json({code :4002, msg:"查询所有医生的数据失败",data})
    }
  };
  DB.connect(sql, [], cb);
})

/**
 * 查询所有医生总数量
 * 
 */
doctorRouter.route("/doctor/count")
.get((req, res)=>{
  DB.connect('select count(*) as count from doctorstable;',[], function(err, data){
    if (!err) {
      res.json({code: 0, msg:'查询成功',data})
    } else {
      res.json({code: 4002, msg:'查询失败',data})
    }
  })
})